<script>
/* scroll down */

var flightResult;//RESULT FOUND
var response;//RESULT FOUND
var sortIndex = 0;
var isContinue = 0;
var flightResultTemp = new Array();
var numOfAjaxRequest = 0;
var progression = 1;
var numOfScroll = 0;

// var carriers = [];
var contextpath = '${pageContext.request.contextPath}';

function sortDropDownList(){
	$("#lbl_sortBy").click();
}

$('document').ready(function(){
	setSubscribleAfterLogin();
});


function sortAirline(){
	sortIndex = 1;
	$("#lbl_sortBy").text('Airlines');
	selectIndex();
	$("#hover1").css("left","-99999px");
	$("#hover1").removeClass("open");
}

function sortNumStop(){
	sortIndex = 2;
	$("#lbl_sortBy").text("Stops");
	selectIndex();
	$("#hover1").css("left","-99999px");
	$("#hover1").removeClass("open");
}

function sortPrice(){
	sortIndex = 0;
	$("#lbl_sortBy").text("Price");
	selectIndex();
	$("#hover1").css("left","-99999px");
	$("#hover1").removeClass("open");
}

function isLoadFromFlightSearch()
{
	var x=document.URL.lastIndexOf(contextpath);
	if (document.URL.length > (x+contextpath.length+1))//include "/" symbol in the last line
		return true;
	return false;
}

function isDisplayResult()
{
	var flag='${sessionScope.markSearch}';
	return flag;
}
function setSubscribleAfterLogin(){
	var str = "logined";
	var pONumb = '${sessionScope.loginBackToSearchResult}';
	
	if (isLoadFromFlightSearch() == true){
		if (isDisplayResult()=="true"){
// 		if(pONumb != str){
			var jsonFlights = '${sessionScope.jsonController}';
			$("#lastPostsLoader").empty();
	    	var arr = jsonFlights.split("#$@#");
	    	flightResult = $.parseJSON(arr[0]);
	    	response = flightResult;
	    	flightLength = arr[1];
	    	jsonParam = $.parseJSON(arr[2]);
	    	var jsonAirlinesStr = arr[4].replace('"[','[');
	    	jsonAirlinesStr = jsonAirlinesStr.replace(']"',']');
	    	jsonParamFilter = $.parseJSON(arr[3]);
	    	jsonAirlines = $.parseJSON(jsonAirlinesStr);
	    	console.log("in login success");
	    	generateHTMLForFilter();
	    	if (flightLength != 0){
	    		 $("#flightLength").html("/"+flightLength);
	    	}
	    	initSlider();
	    	loadSlider();
	    	flightResult = flightResult.filter(function(e) {
				return compare(e);
			});
	    	loadAirlinesName();
	    	loadFlightResult();
	    	sliderFilter();
	    	setValueBackToSearchPanelWhenLoginBackToSubscribe();
	    	unShowLoading();
// 		}
		}
	}
	 <% session.setAttribute("loginBackToSearchResult","out"); %>
}

function setValueBackToSearchPanelWhenLoginBackToSubscribe(){
	var $radios = $('input:radio[name=typeOfTrip]');
	if(jsonParam.typeOfTrip == "oneWay"){
		 $radios.filter('[value=oneWay]').prop('checked', true);
		 $radios.filter('[value=roundTrip]').prop('checked', false);
		 $("#lbReturn").hide();
		 $("#dpd2").hide();
	}

	$("#dpd1").val(jsonParam.outBound);
	$("#dpd2").val(jsonParam.inBound);
	$('#numAdult').val(jsonParam.numAdult).attr("selected", "selected");
	$('#numInfant').val(jsonParam.numInfant).attr("selected", "selected");
	$('#cabinClass').val(jsonParam.cabinClass).attr("selected", "selected");
	$('#numStop').val(jsonParam.numStop).attr("selected", "selected");
	
	//set value back
	var fromCode=jsonParam.fromLocation;
	if(!(fromCode==="")){  //for search page: XXX - name, country
		var fromLocation = (fromCode + "  ").replace(",  ", "").trim();

		var pos1 = fromLocation.indexOf("-");
		var pos3 = fromLocation.lastIndexOf(",");

		fromCode=fromLocation.substring(0, pos1 - 1).trim();
		var fromAirport="";
		var fromCountry="";
		if (pos3 == -1) {
			fromAirport=fromAirportfromLocation.substring(pos1 + 2).trim();
		} else {
			fromAirport=fromLocation.substring(pos1 + 2, pos3).trim();
			fromCountry=fromLocation.substring(pos3 + 2).trim();
		}

		$("#fromInput").tokenInputFixed("add", {
			appLocationType: "Airport",
			airportCode : fromCode,
			airportName : fromAirport,
			countryCode : fromCountry	
		});
	}

	//set value back
	var toCode=jsonParam.toLocation;
	if(!(toCode==="")){  //for search page: XXX - name, country
		var toLocation = (toCode + "  ").replace(",  ", "").trim();

		var pos2 = toLocation.indexOf("-");
		var pos4 = toLocation.lastIndexOf(",");

		toCode=toLocation.substring(0, pos2 - 1).trim();
		var toAirport="";
		var toCountry="";
		if (pos4 == -1) {
			toAirport=toLocation.substring(pos2 + 2).trim();
		} else {
			toAirport=toLocation.substring(pos2 + 2, pos4).trim();
			toCountry=toLocation.substring(pos4 + 2).trim();
		}

		$("#toInput").tokenInputFixed("add", {		
			appLocationType: "Airport",
			airportCode : toCode,
			airportName : toAirport,
			countryCode : toCountry	
		});
	}
		
	var airlineStr = jsonParam.airlines;

	if(airlineStr===""){  //for task
		airlineStr = jsonParam.airlines;
	}

	if (!(airlineStr === "")) {
		var arr = airlineStr.split(";");
		for (var i = 0; i < arr.length; i++) {
			var airline = arr[i].split("-");
			$("#input_autocomplete_airline").tokenInputFixed("add", {
				id_ : 0,
				id : airline[0],
				name : airline[1]
			});
			$(".token-input-list-yolo>.token-input-token-yolo").removeClass("token-input-selected-token-yolo");
		}
	}
}


//get index and sent it to server after sort event.
function selectIndex() {
		//var sortIndex[] =
		var index = response.length;
		console.log("index" + response.length);
		console.log("sortIndex"+ sortIndex);
		response=[];
		if (index >= flightLength) {
			index = flightLength;
		}
		$("#lastPostsLoader").empty();

		//show loading panel in jsloading.jsp
		showLoadingSearchResult();

// 		resetAmountOfAirline();
		ajaxRequest(0, index, sortIndex, true);
	};


$(window).scroll(function() {
	if(response != null){
		if (numOfScroll == 0) {
			numOfScroll = 1;
			$("#footer").css("margin-top","0px");
		}	
		if ($(window).data('ajaxready') == false
					|| $('#loading').is(':visible') || $('#searchResultLoading').is(':visible'))
				return;
			console.log("in scrol down");
			$("#rowSearchPanelLoading").remove();
			var wintop = $(window).scrollTop(), docheight = $(document)
					.height(), winheight = $(window).height();
			var scrolltrigger = 0.95;
			if ((wintop / (docheight - winheight)) > scrolltrigger) {

				//var sortIndex[] =
				var index=response.length;
				if (index >= flightLength) {
					index = flightLength;
					$("#exitScroll").slideUp();
					$("#noResult").slideDown();
					return;
				}
				showLoadingBottomSmall();
				ajaxRequest(index, 10, sortIndex, false);
			}
			$("#span-result-found").html($(".divFlightResult").size());
	}
});

// ajax request function for scroll down
function ajaxRequest(index, offset, sortIndex, isSorting) {
	$(window).data('ajaxready', false);
	var json = {
		"index" : index + "",
		"offset" : offset + "",
		"sortIndex" : sortIndex + ""
	};

	$.ajax({
				url : "${pageContext.request.contextPath}/flight/scrolldown.html",
				data : JSON.stringify(json),
				type : "POST",
				beforeSend : function(xhr) {
					xhr.setRequestHeader("Accept", "application/json");
					xhr
							.setRequestHeader("Content-Type",
									"application/json");
				},
				success : function(jsonFlights) {
					numOfAjaxRequest = numOfAjaxRequest + 1;
					flightResult = $.parseJSON(jsonFlights);
					//insert the new values into response
					response = response.concat(flightResult);
					//re calculate flightResult,
					//display the conditions
					flightResult = flightResult.filter(function(e) {
						return compare(e);
					});

					flightResultTemp = flightResultTemp.concat(flightResult);
					if (flightResultTemp.length < 5) {

						var index=response.length;
						if (index >= flightLength) {
							if(index==0){
								$('#spanResultFoundText').html("RESULT FOUND");
							}else{
							index = flightLength;
							$("#exitScroll").slideUp();
							$("#noResult").slideDown();

							}
						}
						//showLoadingBottomSmall();

						if (index < flightLength) {
							if ((numOfAjaxRequest%5) == 0) {
								progression = progression + 1;
							}

							ajaxRequest(index, 10 * progression * 3, sortIndex, isSorting);

						}
						else {
							numOfAjaxRequest = 0;
							progression = 0;
							flightResult = flightResultTemp;
							loadFlightResult();
							flightResultTemp.length = 0;
							
							unShowLoadingBottomSmall();

							if(isSorting)
								unShowLoadingSearchResult();

							$(window).data('ajaxready', true);
						}
					}
					else {
						flightResult = flightResultTemp;
						loadFlightResult();
						flightResultTemp.length = 0;

						unShowLoadingBottomSmall();

						if(isSorting)
							unShowLoadingSearchResult();

						$(window).data('ajaxready', true);
					};
				},
				error : function() {
					unShowLoadingBottomSmall();
					unShowLoadingSearchResult();
				}
			});
}

//loadData flight result
function loadFlightResult() {
	var contextpath = '${pageContext.request.contextPath}';
	$
			.each(
					flightResult,
					function(index, flight) {
						var divOpen = '<div class="row divFlightResult">'
								+ '<div class="columns">'
								+ '<div class="large-16 medium-16 small-16 columns flight-detail">';
						var divClose = '</div>' + '</div>' + '</div>';
						var subscribe_name = "Subscribe";
						var subscribe_ic = contextpath
								+ "/resources/img/ic_subscribe.png";
						var sub_class = "button subscribe right a-subscribe";
						if (flight.checkSubscribe == 1) {
							subscribe_name = "Unsubscribe";
							subscribe_ic = contextpath
									+ "/resources/img/ic_unsubscribe.png";
							sub_class = "button unsubscribe right a-subscribe";
						}
						var numStops;
						var classType;
						var overOB;

						//Outbound Info
						if (flight.outBound.numberStops > 0) {
							numStops = flight.outBound.numberStops
									+ ' stop(s) '
									+ flight.outBound.airportsExpanded
									+ ' ';
						} else {
							numStops = 'Direct  ';
						}

						if (parseInt(flight.outBound.dayOver)>0){

							overOB="(+"+flight.outBound.dayOver+")";
						}
						else {
							overOB="";
						}
						classType = (flight.outBound.departAirports[0].airline.flightClass == '0') ? 'Economy'
								: 'Business';
						var n = flight.outBound.arriveAirports.length;
						var divOutbound = '<div class="large-6 medium-6 small-6 columns un-padding">'
								+ '<div class="row collapse">'
								+ '<div class="large-2 medium-2 small-4 columns">'
								+ '<img src="' + contextpath + '/resources/img/ic_flight_depart.png" class="flight-icon">'
								+ '</div>'
								+

								'<div class="large-14 medium-14 small-12 columns un-padding">'
								+ '<span class="out-bound-airline">'
								+ flight.outBound.departAirports[0].airline.name.replace(/[^a-zA-Z0-9]/g,' ')
								+ '</span> <br> <span class="gray">'
								+ flight.outBound.departAirports[0].departureTimeYYYYMMDD
								+ '</span><br>'
								+ '<div style="margin-top: 5px;">'
								+ '<span class="green-bold">'
								+ flight.outBound.departAirports[0].code+" "
								+ '</span>'
								+ '<span class="navy">'
								+ flight.outBound.departAirports[0].departureTimeByHHmm
								+ '</span>'
								+ ' - <span class="green-bold">'
								+ flight.outBound.arriveAirports[n - 1].code +"&nbsp"
								+ '</span>'
								+ '<span class="navy">'
								+ flight.outBound.arriveAirports[n - 1].arrivalTimeByHHmm +"&nbsp"
								+ overOB
								+ '</span>'
								+ '<br> <span class="green-bold">'
								+ numStops
								+ '</span>'
								+ '<span class="navy">'
								+ flight.outBound.totalDurationHHMM
								+ '</span>'
								+ '<br> <span class="gray">'
								+ classType
								+ '</span>'
								+ '</div>'
								+ '</div>'
								+ '</div>' + '</div>';
						// Price
						var divPrice = '<div class="large-4 medium-4 columns un-padding">'
								+ '<span class="price"> '
								+ '<font color="red" size="3" id="price" name="vrow">'
								+ flight.price.amount
								+ '</font>'
								+ '<input type="hidden" name="realValue" value='
								+ flight.price.amount
								+ '>'
								+ ' '
								+ '<small><font name="vrowCode" id="currencyCode">'
								+ flight.price.currencyCode
								+ '</font></small>'
								+ ' </span><br>'
								+ '<span class="price-source" style="line-height: 3;"><a target="_blank" href="www.axonactive.vn">www.axonactive.vn</a></span><br><br>'
								+ '<button id="flight'
								+ flight.id
								+ '" value="'
								+ flight.flightID
								+ ','
								+ flight.id
								+ ','
								+ flight.checkSubscribe
								+ '"'
								+ 'class="'
								+ sub_class
								+ '" onclick="sendAjax(value)" name="'
								+ subscribe_name
								+ '">'
								+ '<img src="' + subscribe_ic + '" class="subscribe" /><span style="bottom: 0px;height: 24px;margin-bottom: 0px;position: absolute;left: 33px;font-size: 17px;" >'
								+ subscribe_name
								+ '</span>'
								+ '</button>'
								+ '</div>';
						var finalResult = divOpen + divOutbound + divPrice
								+ divClose;

						// Inbound Info
						if (flight.roundTrip == true) {
							var overIB;
							if (flight.inBound.numberStops > 0) {
								numStops = flight.inBound.numberStops
										+ ' stop(s) '
										+ flight.inBound.airportsExpanded
										+ ' ';
							} else {
								numStops = 'Direct  ';
							}
							if (flight.inBound.dayOver>0){
								overIB="(+" +flight.inBound.dayOver+")";
							}
							else{
								overIB="";
							}
							classType = (flight.inBound.departAirports[0].airline.flightClass == '0') ? 'Economy'
									: 'Business';
							n = flight.inBound.arriveAirports.length;
							var divInbound = '<div class="large-6 medium-6 small-6 columns un-padding">'
									+ '<div class="row collapse">'
									+ '<div class="large-2 medium-2 small-4 columns">'
									+ '<img src="' + contextpath + '/resources/img/ic_flight_return.png" class="flight-icon">'
									+ '</div>'
									+

									'<div class="large-14 medium-14 small-12 columns un-padding">'
									+ '<span class="in-bound-airline">'
									+ flight.inBound.departAirports[0].airline.name.replace(/[^a-zA-Z0-9]/g,' ')
									+ '</span> <br> <span class="gray">'
									+ flight.inBound.departAirports[0].departureTimeYYYYMMDD
									+ '</span><br>'
									+ '<div style="margin-top: 5px;">'
									+ '<span class="green-bold">'
									+ flight.inBound.departAirports[0].code +"&nbsp"
									+ '</span>'
									+ '<span class="navy">'
									+ flight.inBound.departAirports[0].departureTimeByHHmm
									+ '</span>'
									+ '- <span class="green-bold">'
									+ flight.inBound.arriveAirports[n - 1].code  +"&nbsp"
									+ '</span>'
									+ '<span class="navy">'
									+ flight.inBound.arriveAirports[n - 1].arrivalTimeByHHmm +"&nbsp" +overIB
									+ '</span>'
									+ '<br> <span class="green-bold">'
									+ numStops
									+ '</span>'
									+ '<span class="navy">'
									+ flight.inBound.totalDurationHHMM
									+ '</span>'
									+ '<br> <span class="gray">'
									+ classType
									+ '</span>'
									+ '</div>'
									+ '</div>' + '</div>' + '</div>';
							finalResult = divOpen + divOutbound
									+ divInbound + divPrice + divClose;
						}
						$("#lastPostsLoader").append(finalResult);
					});

	$("#span-result-found").html($(".divFlightResult").size());
	changePriceList();
}
</script>